/**************  企业授权(检索	停用	授权)  *********************/
var _common = xbdunRequire("common");
var _targeTable = null;//企业表
var orgInfo = null;//选中行的企业数据

$(function() {
	_targeTable = new TableInit($('#tb_org_info'));
	
	/**************  查询  *****************/
	$("#btn_100100103100_save").on("click",function(){
		if ($("#sel_searchValue").val()!=""&&$("#sel_searchKey").val()==0) {
			return _common.alert(true,"关键字查询,请选择关键字类型");
		}
		$("#bs-100100103100-modal-lg").modal("hide");_targeTable.refresh();
	});
	
	/**************  启用,停用  *****************/
	$("#btn_100100103101").on("click",function(params){
		var _selectOtpns = _targeTable.getSelections();
		if(_selectOtpns&&_selectOtpns.length==1){
			if(orgInfo.blAgentOrg==1){
				return _common.alert(true,"该机构为代理机构,请取消代理机构再进行停用!");
			}
			_common.alert(true,"你确定要"+(orgInfo.enable==1?"停用":"启用")+orgInfo.orgName+"吗?",function(val){if(val==1){
				var temp = {
					id:orgInfo.id,//id 
					enable:orgInfo.enable==1?2:1// 启用状态
				};
				submitData("100100103101", temp, {complete:function(){_targeTable.refresh()}});
			}},2)
		}else{
			_common.alert(true,"请选择一项进行操作.");
		}
	})
	
	/**************  授权  *****************/
	$("#btn_100100103102").on("click",function(params){
		var _selectOtpns = _targeTable.getSelections();
		if(_selectOtpns&&_selectOtpns.length==1){
			if (orgInfo.enable == 2) {
				_common.alert(true,"该企业暂未启用,请启用后再进行授权");
			} else{
				loadingTree(false,"menuTree","100100103102",{orgCode:orgInfo.orgCode});
				var treeObj=$.fn.zTree.getZTreeObj("menuTree");
				if(treeObj){
					var nodes = treeObj.getNodes();
					if(nodes.length>0){
						treeObj.expandNode(nodes[0], true, true, true);
						$("#bs-100100103102-modal-lg").modal("show");
					}else{
						_common.alert(true,"暂无可用菜单,请联系平台先创建菜单!");
					}
				}else{
					_common.alert(true,"加载失败,请刷新再试!");
				}
			}
		}else{
			_common.alert(true,"请选择一项进行操作.");
		}
	});
	/*************  保存授权  *******************/
	$("#btn_100100103102_save").on("click",function(){
		var treeObj = $.fn.zTree.getZTreeObj("menuTree");
		var checkedNodes = treeObj.getCheckedNodes(true);
		var changeNodes = treeObj.getChangeCheckedNodes();
		var addCodes = getAddCodes(checkedNodes,changeNodes);
		var cancelCodes = getCancelCodes(checkedNodes,changeNodes);
		if (addCodes == "" && cancelCodes == ""){
			_common.alert(true,"未进行任何修改!");
		}else {
			submitData("100100103102X", {orgCode:orgInfo.orgCode,addCodesStr:addCodes.join(","),cancelCodesStr:cancelCodes.join(",")}, {complete:function(){$("#bs-100100103102-modal-lg").modal("hide");_targeTable.refresh()}});
		}
	});
	
	/*************  设置代理机构  *******************/
	$("#btn_100100103103").on("click",function(params){
		var _selectOtpns = _targeTable.getSelections();
		if(_selectOtpns&&_selectOtpns.length==1){
			if (orgInfo.enable == 2) {
				return _common.alert(true,"该机构已被停用,请启用后再设置.");
			}
			_common.alert(true,"您确定要"+(orgInfo.blAgentOrg==1?"取消"+orgInfo.orgName+"的":"将"+orgInfo.orgName+"设置为")+"代理机构吗",function(val){if(val==1){
				var temp = {
					orgCode:orgInfo.orgCode,//机构Code
					blAgent:(orgInfo.blAgentOrg==1?2:1)//是否为代理机构
				};
				submitData("100100103103X",temp,{complete:function(){_targeTable.refresh()}});
			}},2)
		}else{
			_common.alert(true,"请选择一项进行操作.");
		}
	});
});

var TableInit = function(targeTbArg) {
	var oTableInit = new Object();
	// 得到查询的参数
	oTableInit.queryParams = function(params) {
		var temp = {
			pageSize: params.pageSize, 						//页面大小
			pageIndex : params.pageIndex, 					//页码
			selectKey:$("#sel_searchKey").val(),			//查询键
			selectValue:$("#sel_searchValue").val(),		//查询值
			auditingStatus:$("#sel_auditingStatus").val(),	//审核状态
			enable:$("#sel_enabled").val(),					//是否启用
			startDate:$("#txt_startDate").val(),			//开始时间
			endDate:$("#txt_endDate").val(),				//结束时间
			blAgentOrg:$("#sel_blAgentOrg").val(),			//是否为代理机构
			orderBy:params.orderBy==null?"enable desc":params.orderBy//排序
		};
		return temp;
	};
	// 初始化Table
	oTableInit.Init = function() {
		return targeTbArg.bootstrapTable("destroy").bootstrapTable({
			url : webRoot+'/system/100100103100', // 请求后台的URL（*）
			queryParams : oTableInit.queryParams,// 传递参数（*）
			uniqueId : "id", // 每一行的唯一标识，一般为主键列
			onCheck:onCheckOrg,
			onUncheck:onUncheck,
			onLoadSuccess:function(d){
				if(d.success){
					if (d.data.data.length) {
						return _targeTable.resetView({height:($('#ifrmContent', parent.document).height()-140)})
					}
				}
				_targeTable.resetView({height:($('#ifrmContent', parent.document).height()-90)})
			},
			height:($('#ifrmContent', parent.document).height()-90),
			columns : [{
				checkbox : true
			}, {
				field : 'orgName',
				title : '企业名称',
				align: 'center',
				valign:'middle',
				formatter : function(value, row, index) {
					switch (row.blAgentOrg||0) {
						case 1: return "<a class='red' href='javascript:void(0)' onClick='showOrgInfo(this)'>【代理机构】"+value+"</a><temp style='display:none'>"+JSON.stringify(row)+"</temp>"
						case 2: return "<a class='blue' href='javascript:void(0)' onClick='showOrgInfo(this)'>"+value+"</a><temp style='display:none'>"+JSON.stringify(row)+"</temp>";	
					}
	            }
			}, {
				field : 'busiPerson',
				title : '企业法人',
				align: 'center',
				valign:'middle'
			}, {
				field : 'orgMobile',
				title : '企业座机/电话',
				align: 'center',
				valign:'middle',
				formatter: function(v,row,index){
					var temp = ' ';
					if(!v&&!row.orgLandline){
						return null;
					}
					if(v){
						temp+= v +",";
					}
					if(row.orgLandline){
						temp+= row.orgLandline +",";
					}
					return temp.substring(0,temp.length-1);
				}
			},{
				field:"orgEmail",
				title:"企业邮箱",
				align: 'center',
				valign:'middle'
			},{
				field:"recordNo",
				title:"备案号",
				align: 'center',
				valign:'middle'
			},{
				field:"auditingTime",
				title:"审核时间",
				align: 'center',
				valign:'middle',
				sortable: true,
				formatter:function(v){
					if(v){return v.substring(0,10);}
				}
			},{
				field:"enable",
				title:"是否启用",
				align: 'center',
				valign:'middle',
				sortable: true,
				formatter: function(v){
					 switch(v||0){
					 	case 1:return "<font color='green'>启用</font>";
					 	case 2:return "<font color='red'>停止</font>";
					 }
				}
			},{
				field:"createTime",
				title:"创建时间",
				align: 'center',
				valign:'middle',
				sortable: true,
				formatter:function(v){
					 if(v){return v.substring(0,10);}
				}
			}
			]
		});
	};
	
	//设置获取选择行
	oTableInit.getSelections = function(){return targeTbArg.bootstrapTable('getSelections');}
	//设置获取所有数据
	oTableInit.getData = function(){return targeTbArg.bootstrapTable('getData');}
	//重新设置视图
	oTableInit.resetView = function(height){return targeTbArg.bootstrapTable('resetView',height);}
	//刷新列表
	oTableInit.refresh = function(){
		//内容刷新
		targeTbArg.bootstrapTable('refresh',{refCallBack:function(){
			_common.loading(false);	//关闭加载
		}})
	}
	//初始化加载数据
	oTableInit.Init();
	return oTableInit;
};

function showOrgInfo(that){
	var $tr = $(that).next("temp");
	if($tr.size()){
		var obj = JSON.parse($tr.text());
		if(!obj["logoUrl"]||!obj["recordImgUrl"]){
			//加载图片
			_common.loading(true,"正在加载,请稍后...");
			$.post(webRoot+"/system/100101104XX",{logo:obj.logo,recordImg:obj.recordImg},function(res){
				setTimeout(function(){
					_common.loading(false);
					if(res){
						if(res.success){
							var _d = JSON.parse(res.data);
							obj["logoUrl"]=_d.logo
							obj["recordImgUrl"]=_d.recordImg;
							$tr.empty().text(JSON.stringify(obj));
							showOrgInfo(that);
						}else{
							_common.alert(true,res.subMsg);
						}
					}
				},1000)
			})
		}else{
			for(var _key in obj){
				if(_key=="logoUrl"||_key=="recordImgUrl"){
					$("#img_"+_key).attr("src",obj[_key]);
				}else{
					var $item = $("#txt_"+_key);
					if($item.size()){
						$item.val(obj[_key]);
					}
				}
			}
			$("#bs-orgInfo-modal-lg").modal("show");
		}
	}
}

/*********************
 * 	调用ajax
 * 
 * @param url		地址
 * @param temp		上传参数
 * @param fnSubmit	回调函数 {success:fn,fail:fn,init:,complete}
 * @returns
 */
function submitData(url, temp, fnSubmit){
	if (fnSubmit.init != null) {
		fnSubmit.init();
	}
	$.ajax({
		type:"post",
		url:webRoot+"/system/"+url,
		data:temp,
		async:false,
		success : function(data) {
			if (data) {
				if (data.success) {
					setTimeout(function(){if(fnSubmit.success != null){fnSubmit.success(data)}},500);
				} else {
					_common.loading(false);
					setTimeout(function(){if(fnSubmit.fail){fnSubmit.fail(data)};_common.alert(true,data.subMsg);},500);
				}
			}
		},
		complete:function (){
				_common.loading(false);
				if (fnSubmit.complete){
					fnSubmit.complete();
				}
		}
	})
}


/*******************  加载树  *********************/
function loadingTree(open,treeName,url,data){
	var setting = {
			data:{
				key:{title:"title"},simpleData:{enable:true,pIdKey:"pid"}
			},
			view:{fontCss:{'font-weight':'bold'},showIcon:false},
			check: {
				enable:true,chkboxType:{"Y":"ps","N":"ps"}
			}
	};
	_common.loading(true, "正在加载中,请稍后...");
	$.ajax({
		type : "post",
		url : webRoot+ "/system/"+url,
		data: data,
		async:false,
		success : function(d) {
			if (d) {
				if (d.success) {
					$.fn.zTree.init($("#"+treeName), setting, d.data);
					$.fn.zTree.getZTreeObj(treeName).expandAll(open);// 将加载的树全部展开
				} else {
					_common.alert(true, d.msg);
				}
			}
			_common.loading(false);
		}
	})
}

/*******************  
 * 求增加的节点
 *   
 **********************/
function getAddCodes (checkedNodes,changeNodes){
	var result = [];
	$.each(changeNodes,function(i,change){
		var bl = false;
		$.each(checkedNodes,function(j,check){
			if (change == check) bl = true;
		})
		if (bl) {
			 result.push (change.id);
		}
	})
	return result;
}
/*******************  
 * 求取消的节点  
 * 初始		最终		选中		改变		
 * #		#		#				
 * #						#		cancel
 * 			#		#		#		add
 * 
 * *********************/
function getCancelCodes  (checkedNodes,changeNodes){
	var result = [];
	$.each(changeNodes,function(i,change){
		var bl = false;
		$.each(checkedNodes,function(j,check){
			if (change == check) bl = true;
		})
		if (!bl) {
			 result.push (change.id);
		}
	})
	return result;
}

function onCheckOrg(row) {
	orgInfo = row;
	if (row.blAgentOrg == 1) {
		$("#btn_100100103103").text("取消代理机构");
	} else {
		$("#btn_100100103103").text("设置代理机构");
	}
}
function onUncheck(row) {
	if (row.blAgentOrg == 1) {
		$("#btn_100100103103").text("设置代理机构");
	}
}